package com.hlt.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlt.dto.UserInfoUpdateDTO;
import com.hlt.entity.UserStats;
import com.hlt.entity.Users;
import com.hlt.mapper.UserStatsMapper;
import com.hlt.mapper.UsersMapper;
import com.hlt.service.IUsersService;
import com.hlt.utils.MD5Util;
import com.hlt.vo.UserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UserStatsMapper userStatsMapper;

    @Override
    public UserInfoVO getUserInfoById(Long userId) {
        Users user = getById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 转换基本信息到VO
        UserInfoVO vo = new UserInfoVO();
        BeanUtils.copyProperties(user, vo);
        vo.setId(Long.valueOf(user.getUserId()));

        // 查询用户统计信息
        UserStats userStats = userStatsMapper.selectById(userId);
        if (userStats != null) {
            vo.setFollowingCount(userStats.getFollowingCount());
            vo.setFollowersCount(userStats.getFollowersCount());
            vo.setLikedPostsCount(userStats.getLikedPostsCount());
            vo.setFavoritedPostsCount(userStats.getFavoritedPostsCount());
        }

        return vo;
    }

    @Override
    public void updateUserInfo(Long userId, UserInfoUpdateDTO dto) {
        Users user = getById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 更新可修改字段（根据业务需求补充）
        if (dto.getNickname() != null) user.setNickName(dto.getNickname());
        if (dto.getAvatarUrl() != null) user.setAvatarUrl(dto.getAvatarUrl());
        if (dto.getEmail() != null) user.setEmail(dto.getEmail());
        if (dto.getPhone() != null) user.setPhone(dto.getPhone());

        updateById(user);
    }

    @Override
    public void updatePassword(Long userId, String oldPassword, String newPassword) {
        Users user = getById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 验证旧密码（假设密码已加密存储，此处使用MD5）
        String encryptedOld = MD5Util.encrypt(oldPassword);
        if (!encryptedOld.equals(user.getPassword())) {
            throw new IllegalArgumentException("旧密码错误");
        }
        // 加密新密码并更新
        String encryptedNew = MD5Util.encrypt(newPassword);
        user.setPassword(encryptedNew);
        updateById(user);
    }
}